<template>
  <div>
    <el-row class="hint-area" v-show="hintVisible">
      <el-col :span="18">
        <span
          class="pad-l-20">当前已【{{this.isMemberWholesaleAuthority === 1 ? '开启' : '关闭'}}】自动授权批发申请，可前往参数设置{{this.isMemberWholesaleAuthority === 1 ? '关闭' : '开启'}}。</span>
        <el-button type="text" @click="linkSetting">立即前往</el-button>
      </el-col>
      <el-col :span="6" align="right">
        <el-button type="info" icon="el-icon-close" class="hint-icon" circle @click="closeHint"></el-button>
      </el-col>
    </el-row>
    <div class="top-operate-default mar-b-20">
      <div class="search-item">
        <label>搜索：</label>
        <el-input v-model="memberListQuery.keyword" @keyup.enter.native="handleSearch" placeholder="昵称/手机号/招募员姓名/招募员手机号"
          style="width: 350px"></el-input>
        <label class="mar-l-20">申请时间：</label>
        <el-date-picker v-model="starEndTime" type="datetimerange" unlink-panels range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </el-button-group>
      </div>
    </div>
    <!-- 操作区域 -->
    <div class="tabs-box mar-t-15">
      <el-tabs type="card" v-model="activeName" class="member-list-tab" @tab-click="handleClick">
        <el-tab-pane :label="waitApproveLabel" name="0"></el-tab-pane>
        <el-tab-pane :label="passLabel" name="1"></el-tab-pane>
        <el-tab-pane :label="rejectLabel" name="2"></el-tab-pane>
      </el-tabs>
    </div>
    <!-- 全选、操作 -->
    <div class="pad-t-15 pad-b-15 font-14">
      <div class="v-align-c" v-if="activeName === '0'">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
            class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
        <el-button class="batch-btn" @click="doBatchUpdateStatus(1)">批量通过</el-button>
        <el-button class="batch-btn" @click="doBatchUpdateStatus(2)">批量拒绝</el-button>
      </div>
    </div>
    <!-- 内容列表 -->
    <div class="table-container">
      <el-table ref="multipleTable" :data="memberList" @selection-change="handleSelectionChange" v-loading="listLoading"
        element-loading-text="加载中" style="width: 100%" header-cell-class-name="default-header"
        row-class-name="default-row">
        <el-table-column width="55px" type="selection"></el-table-column>
        <el-table-column width="320px" label="店主信息" fixed="left">
          <template slot-scope="scope">
            <div class="flex v-align-c">
              <el-tooltip class="item" effect="dark" :content="'微客ID:' + scope.row.memberId" placement="top-start">
                <label><img :src="scope.row.avatar" class="user-avatar" v-if="scope.row.avatar"></label>
              </el-tooltip>
              <div class="font-14 pad-l-10">
                <div><span class="font-color-9">昵称：</span>{{scope.row.nickname}}</div>
                <div><span class="font-color-9">手机：</span>{{scope.row.phone}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="300px" label="来源">
          <template slot-scope="scope">
            <span v-if="scope.row.nature == 1">
              <span>招募员招募</span>
              <br />
              <span>姓名：{{scope.row.rejectLabel}}</span>
              <br />
              <span>手机：{{scope.row.recruiterPhone}}</span>
            </span>
            <span v-if="scope.row.nature == 2">总部招募</span>
          </template>
        </el-table-column>
        <el-table-column width="300px" label="申请时间" prop="createTime"></el-table-column>
        <el-table-column width="300px" label="通过时间" v-if="activeName === '1'">
          <template slot-scope="scope">
            {{scope.row.passDate}}
          </template>
        </el-table-column>
        <el-table-column width="300px" label="拒绝时间" v-if="activeName === '2'">
          <template slot-scope="scope">
            {{scope.row.rejectDate}}
          </template>
        </el-table-column>
        <el-table-column min-width="320px" label="申请资料" prop="memberStore">
          <template slot-scope="scope">
            <div class="font-12 line-h-12">
              <div class="flex">
                <div class="font-color-9 width-60 text-align-r">店铺名称：</div>{{ scope.row.memberStore.storeName }}
              </div>
              <div class="flex">
                <div class="font-color-9 width-60 text-align-r">门店地址：</div>{{ scope.row.memberStore.storeAddress }}
              </div>
              <div class="flex">
                <div class="font-color-9 width-60 text-align-r">门店照片：</div>
                <span class="mar-t-5">
                  <el-image
                    v-if="scope.row.memberStore.imageList != undefined && scope.row.memberStore.imageList.length > 0"
                    style="width: 36px;height: 36px; margin-right: 10px" :src="scope.row.memberStore.imageList[0]"
                    :preview-src-list="scope.row.memberStore.imageList">
                  </el-image>
                </span>
              </div>
              <div class="flex">
                <div class="font-color-9 width-60 text-align-r">联系人：</div>{{ scope.row.memberStore.storeContact }}
              </div>
              <div class="flex">
                <div class="font-color-9 width-60 text-align-r">联系电话：</div>{{ scope.row.memberStore.storePhone }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="操作" align="right" fixed="right" v-if="activeName === '0'">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="doUpdateStatus(scope.row, 1)">通过</el-button>
            <el-button type="text" size="medium" @click="doUpdateStatus(scope.row, 2)">拒绝</el-button>
            <el-button type="text" @click="goApplyDetailMesg(scope.row)">申请详情</el-button>
          </template>
        </el-table-column>
        <el-table-column width="100px" label="操作" align="right" fixed="right" v-if="activeName !== '0'">
          <template slot-scope="scope">
            <el-button type="text" @click="goApplyDetailMesg(scope.row)">申请详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="memberListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="memberListQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 门店照 -->
    <template v-if="shopPicVisible">
      <div class="pic-swiper-box" @click="shopPicVisible = false">
        <el-carousel :interval="5000" arrow="always" indicator-position="none" :autoplay="false" height="650px">
          <el-carousel-item v-for="(item, index) in shopPic" :key="index">
            <div>
              <img :src="item" />
            </div>
            <div class="count font-18 font-color font-white">{{ index + 1 }} / {{ shopPic.length }}</div>
          </el-carousel-item>
        </el-carousel>
      </div>
      <div class="pic-swiper-bg" @click="shopPicVisible = false"></div>
    </template>
    <!-- 提示关闭弹窗 -->
    <el-dialog title="确认操作" width="500px" v-el-drag-dialog :visible.sync="hintOperateVisible">
      <el-radio-group v-model="hintRadio">
        <el-radio label="0">今天不再显示</el-radio>
        <el-radio label="1">我已深知该业务功能配置，不再显示</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hintOperateVisible = false">取消</el-button>
        <el-button type="primary" @click="saveHint">确定</el-button>
      </div>
    </el-dialog>
    <!-- 拒绝弹窗 -->
    <el-dialog title="拒绝原因" width="400px" v-el-drag-dialog :visible.sync="rejectVisible">
      <el-input type="textarea" :rows="3" v-model="opeartDataForm.rejectReason" placeholder="请输入拒绝原因"
        class="pad-l-30 pad-r-30"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rejectVisible = false">取消</el-button>
        <el-button type="primary" @click="doReject">确定</el-button>
      </div>
    </el-dialog>
    <!-- 申请详情 弹窗 -->
    <apply-detail ref="applyDetail"></apply-detail>
  </div>
</template>

<script>
  import {
    getNameByPath
  } from '@/utils/get-name-by-path'
  import {
    pagingMemberRoleAuthority,
    statisticsStatus,
    updateBatchStatus
  } from '@/api/user/memberRoleAuthority'
  import {
    getByEnterpriseId
  } from '@/api/user/enterprise'
  import {
    // updateStatus,
    // batchUpdateStatus,
    updateWholesaleAutoAuthorityHint
  } from '@/api/user/memberAuthority'
  import elDragDialog from '@/directive/el-dragDialog'
  import ApplyDetail from '../apply-detail'

  export default {
    name: getNameByPath(),
    directives: {
      elDragDialog
    },
    components: {
      ApplyDetail
    },
    props: {
      recruiterId: {
        type: String
      },
      showFlag: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        // 日期model
        starEndTime: [],
        memberListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          startDate: null,
          endDate: null,
          keyword: '',
          applyStatus: '',
          memberRoleType: 1 // 微客角色类型：1-批发商，2-主播
        },
        activeName: '0',
        hintRadio: '0',
        total: null,
        listLoading: true,
        // 备注visible
        remarkVisible: false,
        // 自动审核Visible
        hintVisible: false,
        // 自动审核操作Visible
        hintOperateVisible: false,
        // 图片visible
        shopPicVisible: false,
        // 图片数组
        shopPic: [],
        memberList: [],
        multipleSelection: [],
        waitApproveLabel: '待审核',
        passLabel: '已通过',
        rejectLabel: '已拒绝',
        allChecked: false,
        isMemberWholesaleAuthority: 0,
        opeartDataForm: {
          roleAuthorityIds: [],
          memberIds: [],
          status: null,
          rejectReason: ''
        },
        rejectVisible: false,
        dateColumn: 'applyTime'
      }
    },
    filters: {},
    watch: {
      showFlag(val) {
        if (val) {
          // 初始化页面
          this.statisticsStatus()
          this.initMemberRoleAuthority()
          getByEnterpriseId(this.getEnterpriseId()).then(response => {
            if (response.isError) return
            this.hintVisible = response.data.wholesaleAutoAuthorityHint === 1
            this.isMemberWholesaleAuthority = response.data.memberWholesaleAuthority
          })
        }
      }
    },
    created() {},
    mounted() {},
    methods: {
      // 统计
      statisticsStatus() {
        this.waitApproveLabel = '待审核'
        this.passLabel = '已通过'
        this.rejectLabel = '已拒绝'
        statisticsStatus(this.memberListQuery).then(response => {
          if (response.isError) return
          response.data.forEach(item => {
            if (item.typeValue === 0) {
              this.waitApproveLabel += '(' + Math.floor(item.totalCount) + '）'
            }
            if (item.typeValue === 1) {
              this.passLabel += '(' + Math.floor(item.totalCount) + '）'
            }
            if (item.typeValue === 2) {
              this.rejectLabel += '(' + Math.floor(item.totalCount) + '）'
            }
          })
        })
      },
      // 显示申请详情弹窗
      goApplyDetailMesg(item) {
        this.$nextTick(() => {
          this.$refs.applyDetail.setData(item)
          this.$refs.applyDetail.open()
        })
      },
      // 初始化
      initMemberRoleAuthority() {
        this.listLoading = true
        this.memberListQuery.recruiterId = this.recruiterId
        this.memberListQuery.applyStatus = this.activeName
        this.memberListQuery.dateColumn = this.dateColumn
        this.memberListQuery.startDate = (this.starEndTime && this.starEndTime.length > 0) ? this.starEndTime[0] : null
        this.memberListQuery.endDate = (this.starEndTime && this.starEndTime.length > 0) ? this.starEndTime[1] : null
        pagingMemberRoleAuthority(this.memberListQuery).then(response => {
          if (response.isError) return
          this.memberList = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      // tab切换事件
      handleClick() {
        this.memberListQuery.currentPage = 1
        this.initMemberRoleAuthority()
      },
      // 查询事件
      handleSearch() {
        this.memberListQuery.currentPage = 1
        this.initMemberRoleAuthority()
        this.statisticsStatus()
      },
      // 重置
      resetSearch() {
        this.starEndTime = []
        this.memberListQuery = {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          startDate: null,
          endDate: null,
          keyword: '',
          applyStatus: '',
          memberRoleType: 1
        }
        this.statisticsStatus()
        this.initMemberRoleAuthority()
      },
      // 批量通过/拒绝事件
      doBatchUpdateStatus(applyStatus) {
        if (this.multipleSelection.length <= 0) {
          this.$message.error('请选择要操作的数据')
          return
        }
        var roleAuthorityIds = []
        this.multipleSelection.forEach((item) => {
          roleAuthorityIds.push(item.roleAuthorityId)
        })
        var memberIds = []
        this.opeartDataForm.status = applyStatus
        this.opeartDataForm.roleAuthorityIds = roleAuthorityIds
        this.opeartDataForm.memberIds = memberIds
        this.opeartDataForm.rejectReason = ''
        if (this.opeartDataForm.status === 2) {
          this.rejectVisible = true
          return
        }
        this.updateBatchStatusMethod()
      },
      // 通过/拒绝事件
      doUpdateStatus(row, applyStatus) {
        var memberIds = []
        var roleAuthorityIds = []
        roleAuthorityIds.push(row.roleAuthorityId)
        this.opeartDataForm.status = applyStatus
        this.opeartDataForm.roleAuthorityIds = roleAuthorityIds
        this.opeartDataForm.memberIds = memberIds
        this.opeartDataForm.rejectReason = ''
        if (this.opeartDataForm.status === 2) {
          this.rejectVisible = true
          return
        }
        this.updateBatchStatusMethod()
      },
      updateBatchStatusMethod() {
        const title = this.opeartDataForm.status === 1 ? '通过' : '拒绝'
        this.$confirm('是否确认' + title + '？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          updateBatchStatus(this.getEnterpriseId(), this.memberListQuery.memberRoleType,
            this.opeartDataForm.roleAuthorityIds,
            this.opeartDataForm.memberIds,
            this.opeartDataForm.status, null, this.opeartDataForm.rejectReason).then(response => {
            this.rejectVisible = false
            this.allChecked = false
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.msgSuccess(response.msg)
            this.statisticsStatus()
            this.initMemberRoleAuthority()
          })
        })
      },
      doReject() {
        this.updateBatchStatusMethod()
      },
      // 跳转系统参数事件
      linkSetting() {
        this.$router.push({
          path: '/system/system-config/index',
          query: {
            active: 'wholesale-set'
          }
        })
      },
      // 自动审核提示框关闭事件
      closeHint() {
        this.hintRadio = '0'
        this.hintOperateVisible = true
      },
      // 自动审核提示框保存事件
      saveHint() {
        const form = {
          enterpriseId: this.getEnterpriseId(),
          hintSelectStatus: this.hintRadio
        }
        updateWholesaleAutoAuthorityHint(form).then((response) => {
          if (response.isError) return
          this.hintVisible = false
          this.hintOperateVisible = false
        })
      },
      // 图片放大事件
      shopPicEls(data) {
        this.shopPicVisible = true
        this.shopPic = data
      },
      handleSizeChange(val) {
        this.memberListQuery.size = val
        this.initMemberRoleAuthority()
      },
      handleCurrentChange(val) {
        this.memberListQuery.currentPage = val
        this.initMemberRoleAuthority()
      },
      handleSelectionChange(val) {
        this.allChecked = false
        if (this.total > 0) {
          this.multipleSelection = val
          if (this.multipleSelection.length === this.memberList.length) {
            this.allChecked = true
          }
        }
      },
      // 全选事件
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.memberList.length) {
          this.memberList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 59px;
    height: 59px;
    display: block;
    border-radius: 50%;
  }

  .hint-area {
    background-color: #fdf8c8;
    padding: 10px 0;
    margin-bottom: 20px;

    .hint-icon {
      padding: 1px;
      margin: 10px 10px 0 0;
    }
  }

  .el-radio-group {
    padding-left: 5%;

    .el-radio {
      padding-top: 15px;
      display: block;
    }
  }

  .line-h-12 {
    line-height: 1.4;
  }
</style>
